package cn.uncode.baas.server.resource;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import cn.uncode.dal.criteria.Criterion.Condition;
import cn.uncode.dal.descriptor.Column;
import cn.uncode.dal.descriptor.QueryResult;
import cn.uncode.dal.descriptor.Table;
import cn.uncode.dal.descriptor.db.ResolveDataBase;
import cn.uncode.dal.utils.JsonUtils;
import cn.uncode.baas.server.cache.SystemCache;
import cn.uncode.baas.server.constant.Resource;
import cn.uncode.baas.server.dto.RestAdmin;
import cn.uncode.baas.server.dto.RestApp;
import cn.uncode.baas.server.dto.RestTable;
import cn.uncode.baas.server.service.IGenericService;
import cn.uncode.baas.server.service.IResterService;
import cn.uncode.baas.server.utils.AccessTokenUtils;
import cn.uncode.baas.server.utils.DataUtils;
import cn.uncode.baas.server.vo.O2oVo;
import cn.uncode.baas.server.vo.One2manyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;

@Controller
@RequestMapping("/admin/{bucket}")
public class AdminResource extends BaseResource {

    @Autowired
    private IGenericService genericService;

    @Autowired
    private ResolveDataBase resolveDatabase;
    
    @Autowired
    private IResterService resterService;

    @RequestMapping(value = "/original", method = RequestMethod.GET, produces = { "application/json;charset=UTF-8" })
    public @ResponseBody
    ResponseEntity<Object> getOriginalTables(@PathVariable("bucket") String bucket) {
        // query
    	List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
    	initContext(bucket);
    	RestApp restApp = SystemCache.getRestApp(bucket);
    	if(null != restApp){
    		if(StringUtils.isNotEmpty(restApp.getDatabase())){
    			List<String> values = resolveDatabase.loadTables();
    	        List<Map<String,Object>> maps = resterService.loadRestTables(bucket);
    	        for(Map<String,Object> map : maps){
    	        	if(map.containsKey(RestTable.NAME)){
    	        		String name = String.valueOf(map.get(RestTable.NAME));
    	        		if(values.contains(name)){
    	        			values.remove(name);
    	        		}
    	        	}
    	        }
    	        for(String name : values){
    	        	Map<String,Object> item = new HashMap<String,Object>();
    				item.put(RestTable.NAME, name);
    				item.put(RestTable.BUCKET, bucket);
    				result.add(item);
    	        }
    		}
    	}
        clearContext();
        // convert field
        if (null != result && result.size() > 0) {
            return new ResponseEntity<Object>(result, HttpStatus.OK);
        }
        return new ResponseEntity<Object>(HttpStatus.NO_CONTENT);
    }
    
    @RequestMapping(value = "", method = RequestMethod.GET, produces = { "application/json;charset=UTF-8" })
    public @ResponseBody
    ResponseEntity<Object> getTables(@PathVariable("bucket") String bucket) {
        // query
        List<Map<String,Object>> maps = resterService.loadRestTables(bucket);
        // convert field
        if (null != maps && maps.size() > 0) {
            return new ResponseEntity<Object>(maps, HttpStatus.OK);
        }
        return new ResponseEntity<Object>(HttpStatus.NO_CONTENT);
    }

    @RequestMapping(value = "/{table}", method = RequestMethod.GET, produces = { "application/json;charset=UTF-8" })
    public @ResponseBody
    ResponseEntity<Object> getList(@PathVariable("bucket") String bucket, @PathVariable("table") String table,
            WebRequest request) {
        Map<String, Object> maps = DataUtils.convertWebRequest2Map(request);
        initContext(bucket);
        RestApp restApp = SystemCache.getRestApp(bucket);
        // query
        List<String> fields = SystemCache.getRestAdminFields(bucket, table);
        if (fields == null || fields.size() == 0) {
            return new ResponseEntity<Object>(HttpStatus.METHOD_NOT_ALLOWED);
        }
        List<RestAdmin> restAdmins = SystemCache.getRestAdmin(bucket, table);
        Map<String, Object> params = new HashMap<String, Object>();
        for(RestAdmin admin:restAdmins){
        	if(admin.getSearchType() > 0){
        		if(maps.containsKey(admin.getName())){
        			Object value = maps.get(admin.getName());
        			switch (admin.getSearchType()) {
						case Condition.EQUAL:{
							params.put(admin.getName(), value);
							break;
						}
						case Condition.GREATER_THAN:{
							Map<String, Object> valueMap = new HashMap<String, Object>();
							valueMap.put(cn.uncode.baas.server.service.impl.GenericService.Condition.GREATER_THAN, value);
							params.put(admin.getName(), valueMap);
							break;
						}
						case Condition.GREATER_THAN_OR_EQUAL:{
							Map<String, Object> valueMap = new HashMap<String, Object>();
							valueMap.put(cn.uncode.baas.server.service.impl.GenericService.Condition.GREATER_THAN_OR_EQUAL, value);
							params.put(admin.getName(), valueMap);
							break;
						}
						case Condition.LESS_THAN:{
							Map<String, Object> valueMap = new HashMap<String, Object>();
							valueMap.put(cn.uncode.baas.server.service.impl.GenericService.Condition.LESS_THAN, value);
							params.put(admin.getName(), valueMap);
							break;
						}
						case Condition.LESS_THAN_OR_EQUAL:{
							Map<String, Object> valueMap = new HashMap<String, Object>();
							valueMap.put(cn.uncode.baas.server.service.impl.GenericService.Condition.LESS_THAN_OR_EQUAL, value);
							params.put(admin.getName(), valueMap);
							break;
						}
						case Condition.LIKE:{
							Map<String, Object> valueMap = new HashMap<String, Object>();
							valueMap.put(cn.uncode.baas.server.service.impl.GenericService.Condition.LIKE, value);
							params.put(admin.getName(), valueMap);
							break;
						}
						case Condition.NOT_LIKE:{
							Map<String, Object> valueMap = new HashMap<String, Object>();
							valueMap.put(cn.uncode.baas.server.service.impl.GenericService.Condition.NOT_LIKE, value);
							params.put(admin.getName(), valueMap);
							break;
						}
						case Condition.BETWEEN:{
							Map<String, Object> valueMap = new HashMap<String, Object>();
							valueMap.put(cn.uncode.baas.server.service.impl.GenericService.Condition.BETWEEN, value);
							params.put(admin.getName(), valueMap);
							break;
						}
						default:{
							params.put(admin.getName(), value);
							break;
						}
						
					}
        		}
        	}
        }
        if (maps.containsKey("pageIndex")) {
        	params.put("pageIndex", maps.get("pageIndex"));
        }
        if (maps.containsKey("pageSize")) {
        	params.put("pageSize", maps.get("pageSize"));
        }
        if (maps.containsKey("order")) {
        	params.put("order", maps.get("order"));
        }
        QueryResult queryResult = genericService.selectByCriteria(fields, params, table, -1, restApp.getDatabase(), isNoSql(restApp));
        clearContext();
        // convert field
        if (queryResult.getList() != null && queryResult.getList().size() > 0) {
        	for(Map<String, Object> item : queryResult.getList()){
        		if(item.containsKey("_id") && !item.containsKey("id")){
        			item.put("id", item.get("_id"));
        		}
        	}
            return new ResponseEntity<Object>(queryResult.getList(), HttpStatus.OK);
        }
        return new ResponseEntity<Object>(HttpStatus.NO_CONTENT);
    }
    
    @RequestMapping(value = "/{table}/count", method = RequestMethod.GET, produces = { "application/json;charset=UTF-8" })
    public @ResponseBody
    ResponseEntity<Object> count(@PathVariable("bucket") String bucket, @PathVariable("table") String table,
            WebRequest request) {
        Map<String, Object> maps = DataUtils.convertWebRequest2Map(request);
        initContext(bucket);
        RestApp restApp = SystemCache.getRestApp(bucket);
        // query
        List<String> fields = SystemCache.getRestAdminFields(bucket, table);
        if (fields == null || fields.size() == 0) {
            return new ResponseEntity<Object>(HttpStatus.METHOD_NOT_ALLOWED);
        }
        List<RestAdmin> restAdmins = SystemCache.getRestAdmin(bucket, table);
        Map<String, Object> params = new HashMap<String, Object>();
        for(RestAdmin admin:restAdmins){
        	if(admin.getSearchType() > 0){
        		if(maps.containsKey(admin.getName())){
        			Object value = maps.get(admin.getName());
        			switch (admin.getSearchType()) {
						case Condition.EQUAL:{
							params.put(admin.getName(), value);
							break;
						}
						case Condition.GREATER_THAN:{
							Map<String, Object> valueMap = new HashMap<String, Object>();
							valueMap.put(cn.uncode.baas.server.service.impl.GenericService.Condition.GREATER_THAN, value);
							params.put(admin.getName(), valueMap);
							break;
						}
						case Condition.GREATER_THAN_OR_EQUAL:{
							Map<String, Object> valueMap = new HashMap<String, Object>();
							valueMap.put(cn.uncode.baas.server.service.impl.GenericService.Condition.GREATER_THAN_OR_EQUAL, value);
							params.put(admin.getName(), valueMap);
							break;
						}
						case Condition.LESS_THAN:{
							Map<String, Object> valueMap = new HashMap<String, Object>();
							valueMap.put(cn.uncode.baas.server.service.impl.GenericService.Condition.LESS_THAN, value);
							params.put(admin.getName(), valueMap);
							break;
						}
						case Condition.LESS_THAN_OR_EQUAL:{
							Map<String, Object> valueMap = new HashMap<String, Object>();
							valueMap.put(cn.uncode.baas.server.service.impl.GenericService.Condition.LESS_THAN_OR_EQUAL, value);
							params.put(admin.getName(), valueMap);
							break;
						}
						case Condition.LIKE:{
							Map<String, Object> valueMap = new HashMap<String, Object>();
							valueMap.put(cn.uncode.baas.server.service.impl.GenericService.Condition.LIKE, value);
							params.put(admin.getName(), valueMap);
							break;
						}
						case Condition.NOT_LIKE:{
							Map<String, Object> valueMap = new HashMap<String, Object>();
							valueMap.put(cn.uncode.baas.server.service.impl.GenericService.Condition.NOT_LIKE, value);
							params.put(admin.getName(), valueMap);
							break;
						}
						case Condition.BETWEEN:{
							Map<String, Object> valueMap = new HashMap<String, Object>();
							valueMap.put(cn.uncode.baas.server.service.impl.GenericService.Condition.BETWEEN, value);
							params.put(admin.getName(), valueMap);
							break;
						}
						default:{
							params.put(admin.getName(), value);
							break;
						}
						
					}
        		}
        	}
        }
        
        int count = genericService.countByCriteria(params, table, -1, restApp.getDatabase(), isNoSql(restApp));
        clearContext();
        // convert field
        Map<String, Object> result = new HashMap<String, Object>();
        result.put(Resource.REST_SYSTEM_ADMIN_RESOURCES_COUNT_RESULT_KEY, count);
        return new ResponseEntity<Object>(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/{table}/{id}", method = RequestMethod.GET, produces = { "application/json;charset=UTF-8" })
    public @ResponseBody
    ResponseEntity<Object> get(@PathVariable("bucket") String bucket, @PathVariable("table") String table,
            @PathVariable("id") String id, WebRequest request) {
        QueryResult queryResult = null;
        initContext(bucket);
        RestApp restApp = SystemCache.getRestApp(bucket);
        List<String> fields = SystemCache.getRestAdminFields(bucket, table);
        if (fields == null || fields.size() == 0) {
            return new ResponseEntity<Object>(HttpStatus.METHOD_NOT_ALLOWED);
        }
        queryResult = genericService.selectByPrimaryKey(fields, id, table, -1, restApp.getDatabase(), isNoSql(restApp));
        clearContext();
        if (queryResult.get() != null) {
            return new ResponseEntity<Object>(queryResult.get(), HttpStatus.OK);
        }
        return new ResponseEntity<Object>(HttpStatus.NO_CONTENT);
    }

    @RequestMapping(value = "/{table}/info", method = RequestMethod.GET, produces = { "application/json;charset=UTF-8" })
    public @ResponseBody
    ResponseEntity<Object> getInfo(@PathVariable("bucket") String bucket, @PathVariable("table") String table) {
    	initContext(bucket);
    	RestTable restTable = SystemCache.getRestTable(bucket, table);
        RestApp restApp = SystemCache.getRestApp(bucket);
        List<RestAdmin> restAdmins = SystemCache.getRestAdmin(bucket, table);
        if (restAdmins != null) {
            Map<String, Object> result = new HashMap<String, Object>();
            Collections.sort(restAdmins);
            result.put("info", restAdmins);
            Map<String, Object> many2one = resolveMany2oneTables(restApp, restTable);
            Map<String, Object> one2many = resolveOne2manyTables(restApp, restTable);
            if (many2one != null && many2one.size() > 0) {
                result.put("many2one", many2one);
            }
            if (one2many != null && one2many.size() > 0) {
                result.put("one2many", one2many);
            }
            clearContext();
            return new ResponseEntity<Object>(result, HttpStatus.OK);
        }
        clearContext();
        return new ResponseEntity<Object>(HttpStatus.NO_CONTENT);
    }

    @RequestMapping(value = "/{table}/original", method = RequestMethod.GET, produces = { "application/json;charset=UTF-8" })
    public @ResponseBody
    ResponseEntity<Object> getOriginal(@PathVariable("bucket") String bucket, @PathVariable("table") String table) {
        RestTable restTable = SystemCache.getRestTable(bucket, table);
        AccessTokenUtils.checkPermissions(restTable, Resource.REQ_METHOD_GET);
        initContext(bucket);
        RestApp restApp = SystemCache.getRestApp(bucket);
        List<RestAdmin> restAdmins = SystemCache.getRestAdmin(bucket, table);
        Table original = resolveDatabase.loadTable(restApp.getDatabase(), table);
        Map<String, Column> cloumns = original.getContent().getFields();
        Map<String, Column> cloumnsMap = ObjectUtils.clone(cloumns);
        List<RestAdmin> other = new ArrayList<RestAdmin>();
        for (RestAdmin admin : restAdmins) {
            if (cloumnsMap.containsKey(admin.getName())) {
                cloumnsMap.remove(admin.getName());
            }
        }
        for (Column column : cloumnsMap.values()) {
            RestAdmin restAdmin = new RestAdmin();
            restAdmin.setAliasName(column.getName());
            restAdmin.setName(column.getFieldName());
            restAdmin.setMaxLength(column.getLength());
            restAdmin.setType(column.getJdbcType());
            restAdmin.setBucket(bucket);
            restAdmin.setTableName(table);
            other.add(restAdmin);
        }
        restAdmins.addAll(other);
        return new ResponseEntity<Object>(restAdmins, HttpStatus.OK);
    }

    @RequestMapping(value = "/{table}", method = RequestMethod.POST, consumes = { "application/json;charset=UTF-8" })
    ResponseEntity<Object> insert(@PathVariable("bucket") String bucket, @PathVariable("table") String table,
            @RequestBody Map<String, Object> request) {
        if (request == null || request.size() == 0) {
            return new ResponseEntity<Object>(HttpStatus.BAD_REQUEST);
        }
        Map<String, Object> maps = DataUtils.convertWebRequest(request);
        initContext(bucket);
        RestApp restApp = SystemCache.getRestApp(bucket);
        List<String> fields = SystemCache.getRestAdminFields(bucket, table);
        if (fields == null || fields.size() == 0) {
            return new ResponseEntity<Object>(HttpStatus.METHOD_NOT_ALLOWED);
        }
        Object id = genericService.insert(maps, table, restApp.getDatabase(), isNoSql(restApp));
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("result", id);
        clearContext();
        return new ResponseEntity<Object>(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/{table}/{id}", method = RequestMethod.PUT, consumes = { "application/json;charset=UTF-8" })
    ResponseEntity<Object> update(@PathVariable("bucket") String bucket, @PathVariable("table") String table,
            @PathVariable("id") String id, @RequestBody Map<String, Object> request) {
        if (request == null || request.size() == 0) {
            return new ResponseEntity<Object>(HttpStatus.BAD_REQUEST);
        }
        Map<String, Object> maps = DataUtils.convertWebRequest(request);
        initContext(bucket);
        RestApp restApp = SystemCache.getRestApp(bucket);
        genericService.updateByPrimaryKey(id, maps, table, restApp.getDatabase(), isNoSql(restApp));
        clearContext();
        return new ResponseEntity<Object>(HttpStatus.NO_CONTENT);
    }
    
    

    @RequestMapping(value = "/{table}/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<?> delete(@PathVariable("bucket") String bucket, @PathVariable("table") String table,
            @PathVariable("id") String id) {
        initContext(bucket);
        RestApp restApp = SystemCache.getRestApp(bucket);
        genericService.deleteByPrimaryKey(id, table, restApp.getDatabase(), isNoSql(restApp));
        clearContext();
        return new ResponseEntity<Object>(HttpStatus.NO_CONTENT);
    }
    
    @RequestMapping(value = "/{table}/{id}/one2many", method = RequestMethod.GET, produces = { "application/json;charset=UTF-8" })
    ResponseEntity<Object> one2many(@PathVariable("bucket") String bucket, @PathVariable("table") String table,
            @PathVariable("id") String id) {
    	Map<String, Object> rt = new HashMap<String, Object>();
    	QueryResult queryResult = null;
        initContext(bucket);
        RestApp restApp = SystemCache.getRestApp(bucket);
        List<String> fields = SystemCache.getRestAdminFields(bucket, table);
        if (fields == null || fields.size() == 0) {
            return new ResponseEntity<Object>(HttpStatus.METHOD_NOT_ALLOWED);
        }
        RestTable restTable = SystemCache.getRestTable(bucket, table);
        queryResult = genericService.selectByPrimaryKey(fields, Integer.valueOf(id), table, -1, restApp.getDatabase());
        if (queryResult.get() != null) {
        	rt.put("one", queryResult.get());
        }
        One2manyVo vo = restTable.getOne2manyMap().get("id");
        List<String> fds = new ArrayList<String>();
        fds.add(vo.getJoin().getField());
        fds.add(vo.getJoin().getField2());
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(vo.getJoin().getField(), id);
        QueryResult joinResult = genericService.selectByCriteria(fds, params, vo.getJoin()
                .getTable(), -1, restApp.getDatabase());
        List<Object> ids = new ArrayList<Object>();
        if(joinResult.getList() != null && joinResult.getList().size() > 0){
        	for(Map<String, Object> map : joinResult.getList()){
        		ids.add(map.get(vo.getJoin().getField2()));
            }
        }
        QueryResult manyResult = genericService.selectByCriteria(vo.getMany().getFields(), null, vo.getMany()
                .getTable(), -1, restApp.getDatabase());
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        if (manyResult.getList() != null && manyResult.getList().size() > 0) {
            for(Map<String, Object> map : manyResult.getList()){
            	Map<String, Object> item = new HashMap<String, Object>();
            	Object idValue = map.get(vo.getMany().getField());
            	item.put("id", idValue);
            	item.put("name", map.get(vo.getMany().getDisplay()));
            	item.put("flag", ids.contains(idValue));
            	list.add(item);
            }
        }
        rt.put("list", list);
        clearContext();
        return new ResponseEntity<Object>(rt, HttpStatus.OK);
    }
    
    @RequestMapping(value = "/{table}/{id}/{manyId}", method = RequestMethod.POST, consumes = { "application/json;charset=UTF-8" })
    ResponseEntity<Object> addOne2many(@PathVariable("bucket") String bucket, @PathVariable("table") String table,
            @PathVariable("id") String id, @PathVariable("manyId") String manyId, @RequestBody Map<String, Object> request) {
        initContext(bucket);
        RestApp restApp = SystemCache.getRestApp(bucket);
        RestTable restTable = SystemCache.getRestTable(bucket, table);
        One2manyVo one2many = restTable.getOne2manyMap().get("id");
        if(null != one2many){
			if(one2many.isMiddleTableReuse()){
				Map<String, Object> params = new HashMap<String, Object>();
        		params.put(one2many.getJoin().getField(), Integer.parseInt(id));
        		genericService.updateByPrimaryKey(Integer.parseInt(manyId), params, one2many.getMany().getTable(), restApp.getDatabase());
        	}else{
    			Map<String, Object> params = new HashMap<String, Object>();
        		params.put(one2many.getJoin().getField(), Integer.parseInt(id));
        		params.put(one2many.getJoin().getField2(), Integer.parseInt(manyId));
        		genericService.insert(params, one2many.getMany().getTable(), restApp.getDatabase());
        	}
        }
        clearContext();
        return new ResponseEntity<Object>(HttpStatus.NO_CONTENT);
    }
    
    @RequestMapping(value = "/{table}/{id}/{manyId}", method = RequestMethod.DELETE)
    public ResponseEntity<?> delOne2many(@PathVariable("bucket") String bucket, @PathVariable("table") String table,
            @PathVariable("id") String id, @PathVariable("manyId") String manyId) {
    	initContext(bucket);
        RestApp restApp = SystemCache.getRestApp(bucket);
        RestTable restTable = SystemCache.getRestTable(bucket, table);
        One2manyVo one2many = restTable.getOne2manyMap().get("id");
        if(null != one2many){
			if(one2many.isMiddleTableReuse()){
				Map<String, Object> params = new HashMap<String, Object>();
        		params.put(one2many.getJoin().getField(), 0);
        		genericService.updateByPrimaryKey(Integer.parseInt(manyId), params, one2many.getMany().getTable(), restApp.getDatabase());
        	}else{
    			Map<String, Object> params = new HashMap<String, Object>();
        		params.put(one2many.getJoin().getField(), Integer.parseInt(id));
        		params.put(one2many.getJoin().getField2(), Integer.parseInt(manyId));
        		genericService.deleteByCriteria(params, one2many.getMany().getTable(), restApp.getDatabase());
        	}
        }
        clearContext();
        return new ResponseEntity<Object>(HttpStatus.NO_CONTENT);
    }

    /**
     * 
     * @param restApp
     * @param restTable
     * @return
     */
    private Map<String, Object> resolveOne2manyTables(RestApp restApp, RestTable restTable) {
        Map<String, Object> one2many = new HashMap<String, Object>();
        Map<String, One2manyVo> o2map = restTable.getOne2manyMap();
        if (o2map != null) {
        	Map<?,?> info = JsonUtils.jsonToObj(restTable.getOne2many(), Map.class);
        	List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        	if(null != info){
        		Iterator<?> infoIter = info.keySet().iterator();
        		while(infoIter.hasNext()){
        			String key = String.valueOf(infoIter.next());
        			Map<String, Object> value = (Map<String, Object>) info.get(key);
        			value.put(Resource.REST_TABLE_ONE_TO_MANY_ONE_KEY, key);
        			list.add(value);
        		}
        	}
        	one2many.put("info", list);
        }
        return one2many;
    }

    /**
     * 
     * @param restApp
     * @param restTable
     * @return
     */
    private Map<String, Object> resolveMany2oneTables(RestApp restApp, RestTable restTable) {
        Map<String, Object> many2one = new HashMap<String, Object>();
        Map<String, O2oVo> m2oMap = restTable.getMany2oneMap();
        if (m2oMap != null) {
            many2one.put("info", m2oMap);
            Iterator<?> iter = m2oMap.keySet().iterator();
            while (iter.hasNext()) {
                String key = String.valueOf(iter.next());
                O2oVo m2o = m2oMap.get(key);
                QueryResult queryResult = genericService.selectByCriteria(m2o.getFields(), m2o.getOrderMap(),
                        m2o.getTable(), -1, restApp.getDatabase());
                if (queryResult.getList() != null) {
                    many2one.put(key, convertO2oResult(queryResult.getList(), m2o.getField(), m2o.getDisplay(), key));
                }
            }
        }
        return many2one;
    }

    /**
     * 
     * @param list
     * @param field
     * @param display
     * @param key
     * @return
     */
    private Map<String, Object> convertO2oResult(List<Map<String, Object>> list, String field, String display,
            String key) {
        Map<String, Object> rmap = new HashMap<String, Object>();
        if (list != null) {
            for (Map<String, Object> map : list) {
                String[] dis = display.split(",");
                if (dis != null) {
                    StringBuffer sb = new StringBuffer();
                    for (String disField : dis) {
                        sb.append(map.get(disField)).append("-");
                    }
                    if (sb.length() > 0) {
                        rmap.put(String.valueOf(map.get(field)), sb.deleteCharAt(sb.lastIndexOf("-")).toString());
                    }
                }
            }
        }
        return rmap;
    }
    
    private boolean isNoSql(RestApp app) {
		boolean result = true;
		if(null != app){
			if(Resource.REST_APP_DB_TYPE_MYSQL == app.getDbType()){
				result = false;
			}
		}
		return result;
	}

}
